import React, { useState, useEffect } from 'react';
import {
  Table,
  Form,
  Input,
  Button,
  Row,
  Col,
  Drawer,
  Tabs,
  Radio,
  Popconfirm,
  message,
  Typography,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { editAuth } from '../../../api/auth/index';
import PubSub from 'pubsub-js';

function UpdateAuth() {
  const [isUpdateJurisdiction, setIsUpdateJurisdiction] = useState(false);
  const [updateForm] = Form.useForm();
  const [isWhichData, setIsWhichData] = useState({});
  const [isActions, setIsActions] = useState([]);
  const handleAdd = () => {
    tableForm.setFieldsValue({
      action: '',
      name: '',
      describe: '',
    });
    const newData = {
      action: '',
      name: '',
      describe: '',
    };
    setIsActions([...isActions, newData]);
  };
  useEffect(() => {
    PubSub.unsubscribe('showUpdate');
    PubSub.subscribe('showUpdate', (msg, data) => {
      setIsUpdateJurisdiction(true);
      setIsWhichData(data);
      setIsActions(data['actions']);
      updateForm.resetFields();
    });
  });

  const [tableForm] = Form.useForm();
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => {
    console.log('isEditing', record);
    return record.action === editingKey;
  };

  const EditableCell = ({ editing, dataIndex, title, children }) => {
    const inputNode = <Input />;
    return (
      <td>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={
              dataIndex !== 'describe'
                ? [
                    {
                      required: true,
                      message: `请输入${title}!`,
                    },
                  ]
                : [{}]
            }
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  const cancel = () => {
    console.log('取消   ------ ');
    setEditingKey('');
  };
  const save = async (key) => {
    try {
      const row = await tableForm.validateFields();
      const newData = [...isActions];
      const index = newData.findIndex((item) => key === item.action);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setIsActions(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setIsActions(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const edit = (record) => {
    tableForm.setFieldsValue({
      action: '',
      name: '',
      describe: '',
      ...record,
    });
    setEditingKey(record.action);
  };

  const createTableCol = [
    {
      title: '操作类型',
      dataIndex: 'action',
      key: 'action',
      editable: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      editable: true,
    },
    {
      title: '描述',
      dataIndex: 'describe',
      key: 'describe',
      editable: true,
    },
    {
      title: (
        <>
          {'操作 | '}
          <PlusOutlined onClick={handleAdd} />
        </>
      ),
      dataIndex: 'operates',
      key: 'operates',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Popconfirm
              title="确认保存吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => save(record.action)}
            >
              <a
                href="javascript:;"
                style={{
                  marginRight: 8,
                }}
              >
                保存
              </a>
            </Popconfirm>
            |
            <a
              href="javascript:;"
              onClick={() => cancel()}
              style={{ marginLeft: '10px' }}
            >
              取消
            </a>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ''}>
            <a
              href="javascript:;"
              style={{ marginRight: '10px' }}
              onClick={() => edit(record)}
            >
              {'编辑'}
            </a>
            |
            <Popconfirm
              title="确认删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                setIsActions(
                  isActions.filter(
                    (item) =>
                      item.action !== record.action &&
                      item.describe !== record.describe &&
                      item.name !== record.name
                  )
                );
              }}
            >
              <a href="javascript:;" style={{ marginLeft: '10px' }}>
                {'删除'}
              </a>
            </Popconfirm>
          </Typography.Link>
        );
      },
    },
  ];
  const mergedColumns = createTableCol.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  const onClose = () => {
    setIsUpdateJurisdiction(false);
  };

  const { TabPane } = Tabs;

  const onUpdate = (values) => {
    values['describe'] = '';
    values['actions'] = isActions;
    let editData = editAuth(values['id'], values);
    editData.then((item) => {
      message.success(item['msg']);
      PubSub.publish('reset', true);
    });
    onClose();
  };
  return (
    <Drawer
      title="编辑权限"
      placement="right"
      width={'60%'}
      onClose={onClose}
      visible={isUpdateJurisdiction}
      footer={
        <>
          <Button
            onClick={() => {
              updateForm.resetFields();
              onClose();
            }}
            style={{ borderRadius: '4px', marginRight: '10px' }}
          >
            关闭
          </Button>
          <Button
            htmlType="submit"
            style={{ borderRadius: '4px' }}
            type="primary"
            onClick={() => {
              updateForm.submit();
            }}
          >
            保存
          </Button>
        </>
      }
      footerStyle={{ textAlign: 'right' }}
    >
      <Tabs defaultActiveKey="1">
        <TabPane tab="基本信息" key="1">
          <Form
            form={updateForm}
            onFinish={onUpdate}
            initialValues={{
              id: isWhichData['id'],
              name: isWhichData['name'],
              status: isWhichData['status'],
            }}
          >
            <Row>
              <Col span={10} offset={2}>
                <Form.Item
                  rules={[
                    { required: true, message: '只能由字母数字下划线组成' },
                  ]}
                  label="权限标识(ID)"
                  name="id"
                >
                  <Input
                    defaultValue={isWhichData['id']}
                    disabled={true}
                    style={{ borderRadius: '6px' }}
                  />
                </Form.Item>
              </Col>
              <Col span={9} offset={2}>
                <Form.Item
                  rules={[{ required: true, message: '请输入权限名称' }]}
                  label="权限名称"
                  name="name"
                >
                  <Input
                    defaultValue={isWhichData['name']}
                    style={{ borderRadius: '6px' }}
                  />
                </Form.Item>
              </Col>
              <Col span={8} offset={4}>
                <Form.Item
                  rules={[{ required: true, message: '请选择状态' }]}
                  label="状态"
                  name="status"
                >
                  <Radio.Group
                    buttonStyle="solid"
                    defaultValue={isWhichData['status']}
                  >
                    <Radio.Button
                      style={{ borderRadius: '6px 0px 0px 6px' }}
                      value={1}
                    >
                      启用
                    </Radio.Button>
                    <Radio.Button
                      style={{ borderRadius: '0px 6px 6px 0px' }}
                      value={0}
                    >
                      禁用
                    </Radio.Button>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <Form form={tableForm} component={false}>
            <Table
              size="small"
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              title={() => {
                return '操作配置';
              }}
              bordered={true}
              columns={mergedColumns}
              dataSource={isActions}
              pagination={{ onChange: cancel }}
            />
          </Form>
        </TabPane>
      </Tabs>
    </Drawer>
  );
}

export default UpdateAuth;
